在簡單介紹完駐列後,我要將原本的寄信流程改為使用駐列來寄信。
使用資料庫做駐列
env.檔案中的QUEUE_CONNECTION改為:QUEUE_CONNECTION=database
php artisan queue:table
php artisan migrate
做出可以儲存在駐列中的工作php artisan make:job SendEmail
把寄送email的過程改寫到SendEmail的邏輯中
class SendEmail implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $invitedMember;
protected $project;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct(User $invitedMember, Project $project)
{
$this->invitedMember = $invitedMember;
$this->project = $project;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
Mail::to($this->invitedMember->email)
->send(new InvitationInformed($this->invitedMember, $this->project));
}
}
class ProjectInvitationController extends Controller
{
public function store(InvitationRequest $request, Project $project)
{
$validated = $request->validated();
$invitedMember = User::whereEmail($validated['email'])->first();
SendEmail::dispatch($invitedMember,$project);
$project->invite($invitedMember);
return redirect(route('project.show', compact('project')));
}
}
php artisan queue:work
參考文章:
Your Guide to Laravel Email Queues